package es

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/elastic/go-elasticsearch/v6/esapi"
	"strconv"
	"strings"
	"three-sxp/models/mysql"
	"time"
)

func AddEs(index string, order mysql.Goods) error {
	o, _ := json.Marshal(order)
	req := esapi.IndexRequest{
		Index:      index,
		DocumentID: strconv.Itoa(int(order.ID)),
		Body:       strings.NewReader(string(o)),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), EsClient)
	defer res.Body.Close()
	return err
}
func SearchEs(index, title, keyword string) ([]mysql.Goods, error) {
	str := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				title: keyword,
			},
		},
		"highlight": map[string]interface{}{
			"fields": map[string]interface{}{
				title: map[string]interface{}{},
			},
		},
	}
	s, _ := json.Marshal(str)
	res, err := EsClient.Search(
		EsClient.Search.WithContext(context.Background()),
		EsClient.Search.WithIndex(index),
		EsClient.Search.WithBody(strings.NewReader(string(s))),
		EsClient.Search.WithTrackTotalHits(true),
		EsClient.Search.WithPretty(),
	)
	if err != nil {
		return nil, errors.New("es搜索失败")
	}
	defer res.Body.Close()
	var t T
	err = json.NewDecoder(res.Body).Decode(&t)
	if err != nil {
		return nil, errors.New("转换结构体失败")
	}
	var goodsAll []mysql.Goods
	for _, v := range t.Hits.Hits {
		var goods mysql.Goods
		goods.ID = uint(v.Source.ID)
		goods.CreatedAt = v.Source.CreatedAt
		goods.UpdatedAt = v.Source.UpdatedAt
		goods.GoodsName = v.Source.GoodsName
		goods.GoodsPrice = v.Source.GoodsPrice
		goods.GoodsStock = v.Source.GoodsStock
		goods.GoodsDetails = v.Source.GoodsDetails
		goodsAll = append(goodsAll, goods)
	}
	return goodsAll, nil
}

type T struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64 `json:"max_score"`
		Hits     []struct {
			Index  string  `json:"_index"`
			Type   string  `json:"_type"`
			Id     string  `json:"_id"`
			Score  float64 `json:"_score"`
			Source struct {
				ID           int         `json:"ID"`
				CreatedAt    time.Time   `json:"CreatedAt"`
				UpdatedAt    time.Time   `json:"UpdatedAt"`
				DeletedAt    interface{} `json:"DeletedAt"`
				GoodsName    string      `json:"GoodsName"`
				GoodsPrice   float64     `json:"GoodsPrice"`
				GoodsStock   int         `json:"GoodsStock"`
				GoodsDetails string      `json:"GoodsDetails"`
			} `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}
